package com.zhentao.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhentao.es.service.ApArticleSearchService;
import com.zhentao.es.service.ApUserSearchService;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.es.dto.UserSearchDto;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class ApArticleSearchServiceImpl implements ApArticleSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1.检查参数
        if(dto == null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        apUserSearchService.insert(dto.getSearchWords(), 4);

        //2.设置查询条件
        SearchRequest searchRequest=new SearchRequest("app_info_article");
        SearchSourceBuilder builder=new SearchSourceBuilder();

        //布尔查询
        BoolQueryBuilder boolQueryBuilder=new BoolQueryBuilder();

        //关键字查询
        QueryStringQueryBuilder queryStringQueryBuilder =
                QueryBuilders.queryStringQuery(dto.getSearchWords())
                        .field("title")
                        .field("content")
                        .defaultOperator(Operator.OR);

        boolQueryBuilder.must(queryStringQueryBuilder);

        //查询小于mindate的数据
        if(dto.getMinBehotTime() != null){
            RangeQueryBuilder publishTime = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
            boolQueryBuilder.filter(publishTime);
        }

        //分页查询
        builder.from(0);
        builder.size(dto.getPageSize());

        //按照发布时间进行倒叙查询
        builder.sort("publishTime", SortOrder.DESC);

        //设置标题的关键字高亮显示
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red;font-size:20px'>");
        highlightBuilder.postTags("</font>");
        builder.highlighter(highlightBuilder);

        builder.query(boolQueryBuilder);
        searchRequest.source(builder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println(searchRequest);
        System.out.println(search);

        //3.结果封装
        List<Map> list = new ArrayList<>();
        SearchHit[] hits = search.getHits().getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);

            //!! 前端用的是h_title ,所以需要转换一下
            map.put("h_title", map.get("title"));
            //设置高亮
            //"highlight":{"title":["我是一个<font style='color: red;'>测试</font>标题"]}
            if(ObjectUtils.isNotEmpty(hit.getHighlightFields())){
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String join = org.apache.commons.lang.StringUtils.join(titles);
                map.put("h_title", join);
            }
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }
}
